<template>
  <div class="detail">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            class="form"
            label-width="80px"
          >
            <el-form-item prop="username" label="姓名">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input v-model="form.password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateSubmit">更新</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <Info :user-info="initUserInfo" @updateUser="updateUser" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <Job />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser } from '@/api/user'
import { sysUserPut } from '@/api/employees'
export default {
  components: {
    // 异步组件(路由上使用叫做路由懒加载,在组件上使用就叫做异步组件)
    Info: () => import('./components/Info.vue'),
    Job: () => import('./components/Job.vue')
  },
  data() {
    return {
      // 基本传参接收参数
      // id: this.$route.query.id
      // 动态路由匹配传参接收参数
      id: this.$route.params.id,
      userInfo: '',
      initUserInfo: '',
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        password: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 6, max: 12, message: '密码测长度为6-12位', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    const res = await sysUser(this.id)
    this.userInfo = res.data
    // 深拷贝一份用户信息数据
    this.initUserInfo = JSON.parse(JSON.stringify(res.data))
    this.form.username = res.data.username
  },
  methods: {
    updateSubmit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          const data = { ...this.userInfo, ...this.form }
          await sysUserPut(data)
          // 将用户名同步到initUserInfo
          this.initUserInfo.username = this.form.username
          this.$message.success('修改成功')
        }
      })
    },
    // 专门用于子组件更新用户信息
    updateUser(obj) {
      // 子组件修改用户名,同步到父组件中的form.username
      this.form.username = obj.username
      this.userInfo = JSON.parse(JSON.stringify(obj))
    }
  }
}
</script>

<style lang="scss" scoped>
.detail {
  padding: 20px;
  .form {
    width: 500px;
    margin: 20px auto;
  }
}
</style>
